package com.lagou.controller;

import com.lagou.pojo.Result;
import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.TokenService;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Reference
    private UserService userService;

    @Reference
    private TokenService tokenService;


    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable("email") String email, @PathVariable("password") String password,
                            @PathVariable("code") String code, HttpServletResponse response){
        Result result = userService.register(email, password, code);
        if(result.getToken() != null){
            Cookie cookie = new Cookie("token", result.getToken().getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return result.getCode();
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        User user = userService.getByEmail(email);
        if(user != null){
            return true;
        }
        return false;
    }


    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password,
                        HttpServletResponse response){
        User user = userService.getByEmail(email);
        if(user == null){
            return null;
        }
        //校验密码是否正确
        if(!password.equals(user.getPassword())){
            return null;
        }
        Token token = tokenService.createToken(email);
        if(token != null){
            Cookie cookie = new Cookie("token", token.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            return user.getEmail();
        }
        return null;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token){
        Token bo = tokenService.getByToken(token);
        if(bo == null){
            return null;
        }
        return bo.getEmail();
    }
}
